﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Components;

namespace UDS.SubModule.CM
{
    /// <summary>
    /// ClientListView 的摘要说明。
    /// </summary>
    public partial class ClientListViewPage : Page
    {
        private int UserID
        {
            get
            {
                object obj = ViewState["UserID"];
                if (obj == null)
                {
                    return SiteContext.Current.UserID;
                }
                return (int)obj;
            }
            set { ViewState["UserID"] = value; }
        }

        private string UserName
        {
            get
            {
                object obj = ViewState["UserName"];
                if (obj == null)
                {
                    return SiteContext.Current.UserName;
                }
                return (string)obj;
            }
            set { ViewState["UserName"] = value; }
        }

        #region Protected methods

        protected static string GetUpdateTime(DataRow[] row)
        {
            if (row.Length != 0)
            {
                return (row[0]["UpdateTime"].ToString());
            }
            return ("");
        }

        protected static string GetCurStatus(string curstatus)
        {
            switch (curstatus.Split(',')[0])
            {
                case "trace":
                    return ("跟踪");
                case "boot":
                    return ("启动");
                case "commend":
                    return ("产品推荐");
                case "requirement":
                    return ("需求定义");
                case "submit":
                    return ("方案提交");
                case "negotiate":
                    return ("商务谈判");
                case "actualize":
                    return ("项目实施");
                case "traceservice":
                    return ("跟踪服务");
                case "last":
                    return ("收尾款");
            }
            return ("");
        }

        protected static string GetAddMan(DataRow[] row)
        {
            if (row.Length != 0)
            {
                return (row[0]["Realname"].ToString());
            }
            return ("");
        }

        protected static string GetLinkmanTel(DataRow[] row)
        {
            if (row.Length != 0)
            {
                return (row[0]["Mobile"].ToString());
            }
            return ("");
        }

        protected string GetClientNameUrl(string clientid)
        {
            if (ViewState["NowTab"].ToString() == "client")
            {
                return ("Client.aspx?ClientID=" + clientid);
            }
            return ("#");
        }

        protected string GetContactUrl(string clientid)
        {
            if ((ViewState["NowTab"].ToString() == "client") && ((string)Session["cm_permission"] == "administrator"))
            {
                return ("ClientContact_thisWeek.aspx?ClientID=" + clientid);
            }
            return ("ClientHistoryContact.aspx?ClientID=" + clientid);
        }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            // Add event listeners
            btn_Del.Click += btn_Del_Click;
            ddl_MySubordinate.SelectedIndexChanged += ddl_MySubordinate_SelectedIndexChanged;
            lbtn_coClient.Click += lbtn_coClient_Click;
            lbtn_MyClient.Click += lbtn_MyClient_Click;
            dgd_Client.ItemDataBound += dgd_Client_ItemDataBound;
            dgd_Client.SortCommand += dgd_Client_SortCommand;
            dgd_Client.PageIndexChanged += dgd_Client_PageIndexChanged;

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //设置客户权限 默认进入位最高权限'administrator'
                Session["cm_permission"] = "administrator";

                ViewState["SortField"] = "UpdateTime1";
                ViewState["SortDirect"] = "DESC";
                ViewState["NowTab"] = "client";
                BindSubordinate();
                BindGrid();
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// 绑定下级人员
        /// </summary>
        private void BindSubordinate()
        {
            // 绑定下级人员
            var subList = Staff.GetStaffFromPosition(SiteContext.Current.UserName, false);
            ddl_MySubordinate.Items.Clear();
            foreach (var staff in subList)
            {
                ddl_MySubordinate.Items.Add(new ListItem(staff.RealName, staff.ID.ToString()));
            }

            // 加入自己
            string myrealname = "";
            var staffInfo = Staff.GetStaffInfo(SiteContext.Current.UserID);
            if (staffInfo != null)
            {
                myrealname = staffInfo.RealName;
            }
            ddl_MySubordinate.Items.Add(new ListItem(myrealname, SiteContext.Current.UserID.ToString()));

            if (ddl_MySubordinate.Items.Count > 0)
            {
                ListItem listItem = ddl_MySubordinate.Items.FindByValue(UserID.ToString());
                if (listItem != null)
                {
                    ddl_MySubordinate.ClearSelection();
                    listItem.Selected = true;
                }
            }
            else
            {
                ddl_MySubordinate.Visible = false;
            }
        }

        /// <summary>
        /// 绑定我的客户
        /// </summary>
        private void BindGrid()
        {
            TD1.Attributes["background"] = "../../images/maillistbutton2.gif";
            TD2.Attributes["background"] = "../../images/maillistbutton1.gif";

            var cm = new Components.CM();
            var ds = new DataSet();

            DataTable dt_Client;
            using (var dr_Client = cm.GetMyClients(UserID))
            {
                dt_Client = Tools.ConvertDataReaderToDataTable(dr_Client);
            }
            dt_Client.TableName = "Client";
            ds.Tables.Add(dt_Client);

            DataTable dt_Contact;
            using (var dr_Contact = cm.GetClientContactInfo(0))
            {
                dt_Contact = Tools.ConvertDataReaderToDataTable(dr_Contact);
            }
            dt_Contact.TableName = "Contact";
            ds.Tables.Add(dt_Contact);

            DataTable dt_Linkman;
            using (var dr_Linkman = cm.GetAllLinkman())
            {
                dt_Linkman = Tools.ConvertDataReaderToDataTable(dr_Linkman);
            }
            dt_Linkman.TableName = "Linkman";
            ds.Tables.Add(dt_Linkman);

            var staff = new Components.Staff();
            DataTable dt_Staff;
            using (var dr_Staff = staff.GetAllStaffs())
            {
                dt_Staff = Tools.ConvertDataReaderToDataTable(dr_Staff);
            }
            dt_Staff.TableName = "Staff";
            ds.Tables.Add(dt_Staff);

            ds.Relations.Add("ClientAddMan_Staff", ds.Tables["Client"].Columns["AddManID"], ds.Tables["Staff"].Columns["Staff_ID"], false);
            ds.Relations.Add("ClientLinkmanID_Linkman", ds.Tables["Client"].Columns["ChiefLinkmanID"], ds.Tables["Linkman"].Columns["ID"], false);


            ds.Tables["Client"].DefaultView.Sort = (string)ViewState["SortField"] + " " + ViewState["SortDirect"];
            dgd_Client.DataSource = ds.Tables["Client"].DefaultView;
            dgd_Client.DataBind();

            DateTime monthbegin = DateTime.Now.AddMonths(-1);
            var monthend = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));

            int contacttimes = 0;
            using (SqlDataReader dr_ContactTimes = cm.GetContactByStaffIDandTime(UserID, monthbegin, monthend))
            {
                while (dr_ContactTimes.Read())
                {
                    contacttimes++;
                }
            }

            if (Session["cm_permission"].ToString() == "administrator")
            {
                pnl.Visible = true;
                pnl_ClientInfo.Visible = true;
            }
            else
            {
                pnl.Visible = false;
                pnl_ClientInfo.Visible = false;
            }
            //如果没有客户，则 不出现添加 联系人 和 接触情况的 按钮
            btn_AddContact.Visible = (dgd_Client.Items.Count > 0);
            btn_AddLinkman.Visible = (dgd_Client.Items.Count > 0);

            ltl_ClientCount.Text = dt_Client.Rows.Count.ToString();
            ltl_ContactTimes.Text = contacttimes.ToString();
        }

        /// <summary>
        /// 绑定我的协同客户
        /// </summary>
        private void BindMycooperatorClient()
        {
            TD2.Attributes["background"] = "../../images/maillistbutton2.gif";
            TD1.Attributes["background"] = "../../images/maillistbutton1.gif";
            pnl_ClientInfo.Visible = false;
            pnl.Visible = false;

            var cm = new Components.CM();
            var ds = new DataSet();

            SqlDataReader dr_Client = cm.GetClientInfoBycooperatorID(UserID);
            DataTable dt_Client = Tools.ConvertDataReaderToDataTable(dr_Client);
            dt_Client.TableName = "Client";
            ds.Tables.Add(dt_Client);

            SqlDataReader dr_Contact = cm.GetClientContactInfo(0);
            DataTable dt_Contact = Tools.ConvertDataReaderToDataTable(dr_Contact);
            dt_Contact.TableName = "Contact";
            ds.Tables.Add(dt_Contact);

            SqlDataReader dr_Linkman = cm.GetAllLinkman();
            DataTable dt_Linkman = Tools.ConvertDataReaderToDataTable(dr_Linkman);
            dt_Linkman.TableName = "Linkman";
            ds.Tables.Add(dt_Linkman);

            var staff = new Components.Staff();
            SqlDataReader dr_Staff = staff.GetAllStaffs();
            DataTable dt_Staff = Tools.ConvertDataReaderToDataTable(dr_Staff);
            dt_Staff.TableName = "Staff";
            ds.Tables.Add(dt_Staff);

            ds.Relations.Add("ClientAddMan_Staff", ds.Tables["Client"].Columns["AddManID"], ds.Tables["Staff"].Columns["Staff_ID"], false);
            ds.Relations.Add("ClientLinkmanID_Linkman", ds.Tables["Client"].Columns["ChiefLinkmanID"], ds.Tables["Linkman"].Columns["ID"], false);


            ds.Tables["Client"].DefaultView.Sort = (string)ViewState["SortField"] + " " + ViewState["SortDirect"];
            dgd_Client.DataSource = ds.Tables["Client"].DefaultView;
            dgd_Client.DataBind();
        }
        private void dgd_Client_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            object lastSortDirection = ViewState["SortDirection"];
            ViewState["SortDirection"] = ((lastSortDirection == null) || ((string)lastSortDirection == "DESC")) ? "ASC" : "DESC";
            ViewState["SortField"] = e.SortExpression;

            if (ViewState["NowTab"].ToString() == "client")
            {
                BindGrid();
            }
            else
            {
                BindMycooperatorClient();
            }
        }

        private void dgd_Client_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            dgd_Client.CurrentPageIndex = e.NewPageIndex;
            if (ViewState["NowTab"].ToString() == "client")
                BindGrid();
            else
                BindMycooperatorClient();
        }

        private void btn_Del_Click(object sender, EventArgs e)
        {
            string selectedstring = "";
            foreach (DataGridItem dgi in dgd_Client.Items)
            {
                for (int i = 0; i < dgi.Cells[0].Controls.Count; i++)
                {
                    if (dgi.Cells[0].Controls[i].GetType().ToString() == "System.Web.UI.WebControls.CheckBox")
                    {
                        if (((CheckBox)dgi.Cells[0].Controls[i]).Checked)
                        {
                            selectedstring += dgd_Client.DataKeys[dgi.ItemIndex] + ",";
                        }
                    }
                }
            }
            if (selectedstring != "")
            {
                var cm = new Components.CM();
                selectedstring = selectedstring.Substring(0, selectedstring.Length - 1);
                string[] arrselected = selectedstring.Split(',');
                for (int i = 0; i < arrselected.Length; i++)
                {
                    if (arrselected[i].Trim() != "")
                    {
                        cm.DelClient(Int32.Parse(arrselected[i]));
                    }
                }
            }
            BindGrid();
        }

        private void ddl_MySubordinate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((DropDownList)sender).SelectedValue == SiteContext.Current.UserID.ToString())
            {
                Session["cm_permission"] = "administrator";
                pnl.Visible = true;
                pnl_ClientInfo.Visible = true;
            }
            else
            {
                Session["cm_permission"] = "leader";
                pnl.Visible = false;
                pnl_ClientInfo.Visible = false;
            }

            //改变观察视角
            UserID = int.Parse(ddl_MySubordinate.SelectedValue);

            var staffInfo = Staff.GetStaffInfo(UserID, true);
            UserName = staffInfo.Name;

            //重新绑定
            if (ViewState["NowTab"].ToString() == "client")
                BindGrid();
            else
                BindMycooperatorClient();
        }

        private void lbtn_MyClient_Click(object sender, EventArgs e)
        {
            //表示当前用户所在标签
            ViewState["NowTab"] = "client";

            BindGrid();
        }

        private void lbtn_coClient_Click(object sender, EventArgs e)
        {
            //表示当前用户所在标签
            ViewState["NowTab"] = "cooperator";

            BindMycooperatorClient();
        }

        private void dgd_Client_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (ViewState["NowTab"].ToString() == "cooperator")
            {
                Control ctl = e.Item.FindControl("hlk_ClientName");
                if (e.Item.FindControl("hlk_ClientName") != null)
                    ((HyperLink)ctl).Attributes["onclick"] = "alert('你无权查看！');return false;";
            }
        }
    }
}